import json
import os.path
from datetime import datetime

from PyQt5.QtWidgets import QTableWidgetItem


def clear_layout(layout):
    if layout is not None:
        # 删除布局中的所有子控件
        while layout.count():
            item = layout.takeAt(0)
            widget = item.widget()
            if widget is not None:
                widget.deleteLater()
            else:
                # 如果是子布局，递归删除
                clear_layout(item.layout())

        # 从父widget中删除布局
        parent = layout.parent()
        if parent is not None:
            parent.setLayout(None)
            layout.deleteLater()
def getTimeStamp():

    # 获取当前时间戳并转换
    timestamp = datetime.now().timestamp()  # 当前时间戳
    formatted_time = datetime.fromtimestamp(timestamp).strftime("%Y-%m-%d-%H-%M-%S")

    return formatted_time
def modify_row(table_widget, row_index, new_data):
    """修改表格中指定行的数据"""
    for col, value in enumerate(new_data):
        item = QTableWidgetItem(str(value))
        table_widget.setItem(row_index, col, item)
def adjust_columns_width(tablewidget):
    """调整所有列的宽度以适应内容"""
    tablewidget.resizeColumnsToContents()
    # 计算总宽度并设置表格最小宽度
    total_width = sum(tablewidget.columnWidth(i) for i in range(tablewidget.columnCount()))
    tablewidget.setMinimumWidth(total_width + 20 +30)

def saveJson(path,data):
    # if not os.path.exists(path) or not os.path.isfile(path):
    #     return
    with open(path, "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=4)
        f.close()
def readJson(path):
    loaded_data = {}
    if not os.path.exists(path) or not os.path.isfile(path):
        return
    with open(path, "r", encoding="utf-8") as f:
        loaded_data = json.load(f)
        f.close()
    return loaded_data
